package name.weily.liba.tools

import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

abstract class PermissionActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "PermissionActivity"
    }

    private var unRequested: MutableList<String>? = null
    private var autoFinishing = false

    protected fun checkPermissions(permissions: Array<String>) {

    }

    protected fun applyPermissions(permissions: Array<String>, autoFinish: Boolean = false) : Boolean {
        autoFinishing = autoFinish
        unRequested = permissions.filter {
            ContextCompat.checkSelfPermission(this@PermissionActivity, it) != PackageManager.PERMISSION_GRANTED
        }.toMutableList()

       return checkApply()
    }

    private fun checkApply() : Boolean {
        Log.d(TAG, "checkApply permission: $unRequested")
        unRequested?.also {
            if (it.size > 0) {
                val ret = requestPermission(it[0])
                Log.d(TAG, "requesting  ${it[0]} = $ret")
                return ret == 0
            } else {
                if (autoFinishing) {
                    finish()
                }
                return true
            }
        } ?: return true
        return false
    }

    /**
     * @return 0: already requested; 1: delay
     */
    private fun requestPermission(permission: String) : Int {
        if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) {
            return 0
        } else {
            ActivityCompat.requestPermissions(this, arrayOf(permission), 100)
            return 1
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == 100) {
            grantResults.forEachIndexed { index, grantRes ->
                if (grantRes == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "${permissions[index]} request success!", Toast.LENGTH_SHORT).show()
                    unRequested?.removeAt(index)
                    checkApply()
                } else {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[index])) {
                        val builer = AlertDialog.Builder(this@PermissionActivity).apply {
                            setTitle("Permission")
                            setMessage("Allow permission to use APP")
                            setPositiveButton("Go") { dialog: DialogInterface, which: Int ->
                                dialog.dismiss()
                                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                                val uri = Uri.fromParts("package", packageName, null)//注意就是"package",不用改成自己的包名
                                intent.setData(uri)
                                startActivityForResult(intent, 200)
                            }
                        }
                        val dialog = builer.create()
                        dialog.setCanceledOnTouchOutside(false)
                        dialog.show()
                    } else {
                        val builer = AlertDialog.Builder(this@PermissionActivity).apply {
                            setTitle("Permission")
                            setMessage("Allow permission to use APP")
                            setPositiveButton("Go") { dialog: DialogInterface, which: Int ->
                                dialog.dismiss()
                                requestPermission(permissions[index])
                            }
                        }
                        val dialog = builer.create()
                        dialog.setCanceledOnTouchOutside(false)
                        dialog.show()
                    }
                }
            }
        }
    }

    protected fun resize(x: Int, y: Int, w: Int, h: Int) {
        window?.also {
            it.setGravity(Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM)
            it.attributes.x = x
            it.attributes.y = y
            it.attributes.width = w
            it.attributes.height = h
        }
    }
}

